package com.dys.hejiayuncommunity.system.service.impl;

import com.dys.hejiayuncommunity.common.constant.Constants;
import com.dys.hejiayuncommunity.common.core.exception.BaseException;
import com.dys.hejiayuncommunity.common.core.exception.CaptchaNotMatchException;
import com.dys.hejiayuncommunity.common.utils.RedisCache;
import com.dys.hejiayuncommunity.system.domain.LoginUser;
import com.dys.hejiayuncommunity.system.service.SysLoginService;
import com.dys.hejiayuncommunity.system.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

/**
 * @className: com.dys.hejiayuncommunity.system.service.impl.SysLoginServiceImpl
 * @description: 登录校验
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/12/19 22:15
 */
@Service
public class SysLoginServiceImpl implements SysLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;

    @Override
    public String login(String username, String password, String code, String uuid) {
        // 1.从redis中获取验证码,判断是否正确
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null || !code.equalsIgnoreCase(captcha)) {
            throw new CaptchaNotMatchException();
        }
        // 2.进行用户认证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            throw new BaseException("用户不存在或密码错误");
        }
        // 3. 获取经过身份验证的用户的主体信息
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 4.调用TokenService 生成token
        return tokenService.createToken(loginUser);
    }
}
